package com.dunqi.gpm.cangxi.home.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dunqi.gpm.cangxi.R;
import com.dunqi.gpm.cangxi.common.api.ApiFactory;
import com.dunqi.gpm.cangxi.common.api.RxSchedulers;
import com.dunqi.gpm.cangxi.common.base.BaseFragment;
import com.dunqi.gpm.cangxi.common.base.ComObserver;
import com.dunqi.gpm.cangxi.common.base.Data;
import com.dunqi.gpm.cangxi.common.util.SwipeUtil;
import com.dunqi.gpm.cangxi.common.view.NoScrollGridView;
import com.dunqi.gpm.cangxi.common.view.RecyclerItemDecoration;
import com.dunqi.gpm.cangxi.home.activity.YearPlanDetailActivity;
import com.dunqi.gpm.cangxi.home.adapter.YearPlanAdapter;
import com.dunqi.gpm.cangxi.home.bean.Page;
import com.dunqi.gpm.cangxi.home.bean.Project;
import com.dunqi.gpm.cangxi.home.bean.YearPlan;
import com.dunqi.gpm.cangxi.home.constance.Constance;
import com.dunqi.gpm.cangxi.home.widget.EmptyView;
import com.dunqi.gpm.cangxi.home.widget.NormalView;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2017/11/26.
 */

public class YearPlanListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    private Project project;
    int page = 1;
    ArrayList<YearPlan> data = new ArrayList<>();
    private YearPlanAdapter adapter;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }
    @SuppressLint("CheckResult")
    private void net() {
        ApiFactory.getInstance()
                .queryProjectAnnualPlanList(project.getProjectId(), page)
                .compose(RxSchedulers.<Page<YearPlan>>io_main())
                .subscribe(yearPlanPage -> {
                    ArrayList<YearPlan> list = yearPlanPage.getList();
                    boolean hasNextPage = yearPlanPage.isHasNextPage();
                    if (page == 1) {
                        data.clear();
                    }
                    data.addAll(list);
                    adapter.notifyDataSetChanged();
                    page++;
                    SwipeUtil.loadCompleted(swipeRefresh);
                    if (data.size() > 0) {
                        if (footerView != null)//现在不需要再下方展示
                            getYearPlan(list.get(0).getProjectId(), list.get(0).getPlanYear());
                    }
                    if (!hasNextPage) {
                        adapter.loadMoreEnd(true);
                        return;
                    } else {
                        adapter.loadMoreComplete();
                    }
                }, throwable -> {
                    SwipeUtil.loadCompleted(swipeRefresh);
                    adapter.loadMoreFail();
                });
    }

    @Override
    protected void initUiAndListener() {
        recycler.setLayoutManager(new LinearLayoutManager(context));
        adapter = new YearPlanAdapter(data);
        recycler.setAdapter(adapter);
        recycler.addItemDecoration(new RecyclerItemDecoration(1, RecyclerItemDecoration.VERTICAL));
        swipeRefresh.setOnRefreshListener(this);
        adapter.setOnLoadMoreListener(this, recycler);
        adapter.setOnItemClickListener(this);
        adapter.setEmptyView(new EmptyView(context));
//        footerView = LayoutInflater.from(getActivity()).inflate(R.layout.projict_yerars_content, null);
//        // footerView.setVisibility(View.GONE);
//        adapter.setFooterView(footerView);
//        initFooter();
    }

    View footerView;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_year_plan;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        project = (Project) arguments.getSerializable(Constance.PROJECT);
    }

    public static YearPlanListFragment newInstance(Project project) {
        YearPlanListFragment fragment = new YearPlanListFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constance.PROJECT, project);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onRefresh() {
        page = 1;
        net();
    }

    @Override
    public void onLoadMoreRequested() {
        net();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        YearPlan yearPlan = data.get(position);
        YearPlanDetailActivity.start(context, yearPlan.getPlanYear(), yearPlan.getProjectId());
    }

    //年度内容详情 (以前 在YearPlanDetailActivity 中展示,现在移出来)--------------start------------------
    TextView title1Tv;
    NormalView reportCycleView;
    NormalView planStartTimeView;
    NormalView planEndTimeView;
    NormalView buildKindView;
    NormalView lastYearCompletedMoneyView;
    NormalView lastYearImageProgressView;
    NormalView wholeYearContentTv;
    TextView title2Tv;
    NormalView totalMoneyView;
    NormalView centerMoneyView;
    NormalView provinceMoneyView;
    NormalView cityMoneyView;
    NormalView countyMoneyView;
    NormalView bankMoneyView;
    NormalView getMoneyView;
    NormalView privateMoneyView;
    NormalView financingView;
    NormalView otherMoneyView;
    NormalView determinedMoneyView;
    NormalView desView;
    TextView title3Tv;
    NoScrollGridView gridView;
    ScrollView scrollView;

    NormalView centerBankMoneyView;
    NormalView factoryBankMoneyView;
    NormalView agriculturalBankMoneyView;
    NormalView ccbMoneyView;

    void initFooter() {
        title1Tv = footerView.findViewById(R.id.title_1_tv);
        reportCycleView = footerView.findViewById(R.id.report_cycle_view);
        planStartTimeView = footerView.findViewById(R.id.plan_start_time_view);
        planEndTimeView = footerView.findViewById(R.id.plan_end_time_view);
        buildKindView = footerView.findViewById(R.id.build_kind_view);
        lastYearCompletedMoneyView = footerView.findViewById(R.id.last_year_completed_money_view);
        lastYearImageProgressView = footerView.findViewById(R.id.last_year_Image_progress_view);
        wholeYearContentTv = footerView.findViewById(R.id.whole_year_content_tv);
        title2Tv = footerView.findViewById(R.id.title_2_tv);
        totalMoneyView = footerView.findViewById(R.id.total_money_view);
        centerMoneyView = footerView.findViewById(R.id.center_money_view);
        provinceMoneyView = footerView.findViewById(R.id.province_money_view);
        cityMoneyView = footerView.findViewById(R.id.city_money_view);
        countyMoneyView = footerView.findViewById(R.id.county_money_view);
        bankMoneyView = footerView.findViewById(R.id.bank_money_view);
        getMoneyView = footerView.findViewById(R.id.get_money_view);
        privateMoneyView = footerView.findViewById(R.id.private_money_view);
        financingView = footerView.findViewById(R.id.financing_view);
        otherMoneyView = footerView.findViewById(R.id.other_money_view);
        determinedMoneyView = footerView.findViewById(R.id.determined_money_view);
        desView = footerView.findViewById(R.id.des_view);
        title3Tv = footerView.findViewById(R.id.title_3_tv);
        gridView = footerView.findViewById(R.id.grid_view);
        scrollView = footerView.findViewById(R.id.scrollView);
        centerBankMoneyView = footerView.findViewById(R.id.center_bank_money_view);
        factoryBankMoneyView = footerView.findViewById(R.id.factory_bank_money_view);
        agriculturalBankMoneyView = footerView.findViewById(R.id.agricultural_bank_money_view);
        ccbMoneyView = footerView.findViewById(R.id.ccb_money_view);
    }

    void getYearPlan(long projectId, int year) {
        ApiFactory.getInstance()
                .queryProjectAnnualPlanInfo(projectId, year)
                .compose(RxSchedulers.<Data<YearPlan>>io_main())
                .subscribe(new ComObserver<YearPlan>() {
                    @Override
                    public void onSuccess(YearPlan yearPlan) {
                        if (yearPlan == null) {
                            return;
                        }
                        footerView.setVisibility(View.VISIBLE);
                        refreshUi(yearPlan);

                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                });
    }

    private void refreshUi(YearPlan yearPlan) {
        title1Tv.setVisibility(View.GONE);
        reportCycleView.setVisibility(View.GONE);
        financingView.setVisibility(View.GONE);
        otherMoneyView.setVisibility(View.GONE);
        determinedMoneyView.setVisibility(View.GONE);

        title1Tv.setText(yearPlan.getPlanYear() + "年年度计划");
        title2Tv.setText(yearPlan.getPlanYear() + "年年度投资计划(万元)");
        title3Tv.setText(yearPlan.getPlanYear() + "年每月形象进度");

        String reportFrequency = yearPlan.getReportFrequency();
        String text;
        if ("report_per_month".equals(reportFrequency)) {
            text = "按月汇报\n每月21日自动生成待汇报，汇报时限是7天";
        } else if ("report_per_10days".equals(reportFrequency)) {
            text = "按旬汇报\n每月9、19、29日自动生成待汇报，汇报时限是1天";
        } else {
            text = "无需汇报";
        }
        reportCycleView.setText(text);

        planStartTimeView.setText(yearPlan.getPlanStartTime());
        planEndTimeView.setText(yearPlan.getPlanCompleteTime());
        buildKindView.setText(yearPlan.getConstructionTypeText());
        lastYearCompletedMoneyView.setText(String.valueOf(yearPlan.getCompletedFundLastYear()));
        lastYearImageProgressView.setText(yearPlan.getProgressDescLastYear());
        wholeYearContentTv.setText(yearPlan.getConstructionDescWholeYear());

        totalMoneyView.setText(String.valueOf(yearPlan.getTotalInvestmentAmount()));
        centerMoneyView.setText(String.valueOf(yearPlan.getNationalFund()));
        privateMoneyView.setText(String.valueOf(yearPlan.getProvinceFund()));
        cityMoneyView.setText(String.valueOf(yearPlan.getMunicipalFund()));
        countyMoneyView.setText(String.valueOf(yearPlan.getConuntyFund()));
        bankMoneyView.setText(String.valueOf(yearPlan.getBankLoadFund()));
        getMoneyView.setText(String.valueOf(yearPlan.getAttractInvestmentFund()));
        privateMoneyView.setText(String.valueOf(yearPlan.getSelfFund()));
        financingView.setText(String.valueOf(yearPlan.getRaisingFund()));
        otherMoneyView.setText(String.valueOf(yearPlan.getOtherFund()));
        determinedMoneyView.setText(String.valueOf(yearPlan.getUndeterminedFund()));
        desView.setText(String.valueOf(yearPlan.getFundSourceDesc()));

        centerBankMoneyView.setText(String.valueOf(yearPlan.getBocLoadFund()));
        factoryBankMoneyView.setText(String.valueOf(yearPlan.getIcbcLoadFund()));
        agriculturalBankMoneyView.setText(String.valueOf(yearPlan.getAbcLoadFund()));
        ccbMoneyView.setText(String.valueOf(yearPlan.getCcbLoadFund()));

        String[] visualProgresses = yearPlan.getVisualProgresses();

        LinearLayout ll_ydxx = footerView.findViewById(R.id.ll_ydxx);
        ll_ydxx.removeAllViews();
        for (int i = 0; i < visualProgresses.length; i++) {
            NormalView normalView = new NormalView(getActivity());
            normalView.setdesLength(8);
            normalView.setDes((i + 1) + "月形象进度:");
            normalView.setText(visualProgresses[i]);
            ll_ydxx.addView(normalView, i);
        }
    }
    //年度内容详情 (以前 在YearPlanDetailActivity 中展示,现在移出来)--------------end------------------
}